package com.xcc;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class Client extends Thread {
    public Client(Socket socket) {
        this.socket = socket;
    }

    private Socket socket;
    private ClientListener clientListener;

    public Client setClientListener(ClientListener clientListener) {
        this.clientListener = clientListener;
        return this;
    }

    public void run() {
        // 接收信息
        try {
            while (true) {
                String msg = "";
                InputStream inputStream = socket.getInputStream();

                byte[] bs = new byte[100];
                int i = 0;
                while ((i = inputStream.read(bs)) > 0) {
                    msg += new String(bs, 0, i);
                    if (i < 100) {
                        break;
                    }
                }
                //inputStream.close();
                if (msg.length() > 0) clientListener.acceptMsg(this, msg);
            }
        } catch (IOException e) {
            // e.printStackTrace();
        }
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        clientListener.clientOut(this);
    }

    public void sendMsg(String msg) {
        try {
            OutputStream outputStream = socket.getOutputStream();
            // outputStream.write((msg + "\n").getBytes());
            outputStream.write(msg.getBytes());
            outputStream.flush();
            //outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public interface ClientListener {
        void acceptMsg(Client client, String msg);

        void clientOut(Client client);
    }
}
